package com.itheima.dateSync.service.impl;

import com.heima.model.common.VO.SearchArticleVO;
import com.heima.model.common.artcle.pojo.ApArticle;
import com.heima.model.common.constants.es.EsConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.itheima.common.exception.CustException;
import com.itheima.dateSync.mapper.ApArticleMapper;
import com.itheima.dateSync.service.EsDataService;
import com.heima.es.service.EsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    private EsService<SearchArticleVO> esService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Override
    public ResponseResult dataInit() {
        //判断索引库是否存在
        boolean exist = esService.existIndex(EsConstants.ARTICLE_INDEX_NAME);
        if (exist){
            //存在 删除
            esService.deleteIndex(EsConstants.ARTICLE_INDEX_NAME);
        }
        esService.createIndex(EsConstants.CREAT_INDEX_WORD,EsConstants.ARTICLE_INDEX_NAME);
        //查询文章列表
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        if (allArticles==null || allArticles.size()==0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<SearchArticleVO> searchArticleVOS = new ArrayList<>();
        for (ApArticle allArticle : allArticles) {
            SearchArticleVO searchArticleVO = new SearchArticleVO();
            BeanUtils.copyProperties(allArticle,searchArticleVO);
            searchArticleVOS.add(searchArticleVO);
        }
        esService.saveBatch(searchArticleVOS,EsConstants.ARTICLE_INDEX_NAME);
        return ResponseResult.okResult();
    }

}
